package com.xinggq.pay.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinggq.pay.service.entity.PayOrderEntity;
import com.xinggq.pay.service.enums.PayChannelEnum;
import com.xinggq.pay.service.mapper.PayOrderMapper;
import com.xinggq.pay.service.service.PayOrderService;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 支付订单服务实现类
 * @author xinggq
 * @since 2025/9/16
 */
@Slf4j
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrderEntity> implements PayOrderService {

    @Override
    public PayOrderEntity findByTradeNo(String tradeNo) {
        if (!StringUtils.hasText(tradeNo)) {
            throw new IllegalArgumentException("平台订单号不能为空");
        }
        
        LambdaQueryWrapper<PayOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PayOrderEntity::getTradeNo, tradeNo);
        
        return this.getOne(queryWrapper);
    }

    @Override
    public PayOrderEntity findByMerchantOrderNo(String merchantOrderNo) {
        if (!StringUtils.hasText(merchantOrderNo)) {
            throw new IllegalArgumentException("商户订单号不能为空");
        }
        
        LambdaQueryWrapper<PayOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PayOrderEntity::getMerchantOrderNo, merchantOrderNo);
        
        return this.getOne(queryWrapper);
    }

    @Override
    public PayOrderEntity findByChannelTradeNoAndChannelType(String channelTradeNo, PayChannelEnum payChannelType) {
        if (!StringUtils.hasText(channelTradeNo)) {
            throw new IllegalArgumentException("支付渠道订单号不能为空");
        }
        if (Objects.isNull(payChannelType)) {
            throw new IllegalArgumentException("支付渠道类型不能为空");
        }
        
        LambdaQueryWrapper<PayOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PayOrderEntity::getChannelTradeNo, channelTradeNo)
                   .eq(PayOrderEntity::getChannelType, payChannelType.getCode());
        return this.getOne(queryWrapper);
    }
}